#include "ecv_server.h"

#define ECV_WIDTH 640
#define ECV_HEIGHT 480
#define ECV_BPP 24
#define ECV_XDIV 144
#define ECV_YDIV 34
#define ECV_THR 10

int main (int argc, char **argv)
{
  ecv_init();
  EcvVi * vi = ECV_VI(ecv_vi_v4l2_new(ECV_WIDTH,ECV_HEIGHT,ECV_BPP,"/dev/video1"));
  EcvVo * vo = ecv_vo_new(ECV_WIDTH,ECV_HEIGHT,ECV_BPP,"ECV vo");

  printf ("creating grayscale filter\n");
  EcvFilter_Grayscale * gscl = ecv_filter_grayscale_new(ECV_WIDTH,ECV_HEIGHT,ECV_BPP);
  EcvFilter * fgscl = ECV_FILTER(gscl);

  printf ("creating binarize filter\n");
  EcvFilter * bicl = ECV_FILTER(ecv_filter_binarize_new(ECV_WIDTH, ECV_HEIGHT, ECV_BPP, ECV_XDIV, ECV_YDIV));

  printf ("creating conventional hough transform filter\n");
  EcvFilter * fch = ECV_FILTER(ecv_filter_convhough_new(ECV_WIDTH, ECV_HEIGHT, ECV_BPP));

  ecv_filter_create(fch);
  ecv_filter_create(fgscl);
  ecv_filter_create(bicl);

  EcvImage * img = ecv_image_new(ECV_WIDTH, ECV_HEIGHT, ECV_BPP);
  
  ecv_vi_create(vi);
  ecv_vo_create(vo);

  ecv_image_create(img);

  ecv_vi_run(vi);

  if (ecv_vi_failed(vi))
    return -1;

  int run = 1;

  char * bufi = NULL;
  char * buft = NULL;
  char * bufo = NULL;
  int dataszi = 0;
  int dataszt = 0;
  int dataszo = 0;

  unsigned int framesctr = 0;
  
  int t0 = 0;
  int frames = 0;
  int t;
  
  while (run)
    {
      ecv_vi_step_begin (vi);

      bufi = ecv_vi_get_data (vi);
      
      if (bufi == NULL)
	{
	  run = 0;
	  break;
	}
      
      dataszi = ecv_vi_get_data_size (vi);
      framesctr = framesctr+1;
      frames = frames+1;

      printf ("video buffer acquired, datasz = %i\n", dataszi);

      ecv_image_set (img, bufi, dataszi);

      buft = ecv_image_get_data (img);
      dataszt = ecv_image_get_data_size (img);

      ecv_filter_set(fgscl, buft, dataszt);
      ecv_filter_process(fgscl);
      bufo = ecv_filter_get_data (fgscl);
      dataszo = ecv_filter_get_data_size (fgscl);

      ecv_filter_set(bicl, bufo, dataszo);
      ecv_filter_process(bicl);
      ecv_filter_binarize_preparetodraw(ECV_FILTER_BINARIZE (bicl), 0, 0, ECV_THR, 1);
      bufo = ecv_filter_get_data (bicl);

      ecv_filter_set(fch, bufo, dataszt);
      ecv_filter_process(fch);
      ecv_filter_convhough_preparetodraw(ECV_FILTER_CONVHOUGH(fch));
      bufo = ecv_filter_get_data (fch);
      
      ecv_vo_set (vo, bufo, dataszo);
      //ecv_vo_set (vo, bufi, dataszi);
      ecv_vo_draw (vo);
      ecv_vo_events (vo);

      if (ecv_vo_get_quit(vo) == 1)
	run = 0;
      
      t = SDL_GetTicks();
      if (t - t0 >= 5000) 
	{
	  float seconds = (t - t0) / 1000.0;
	  float fps = frames / seconds;
	  printf("\r");
	  printf("%d frames in %g seconds = %g fps\n", frames, seconds, fps);
	  t0 = t;
	  frames = 0;
	}

      ecv_vi_step_end (vi);
    }
  ecv_filter_convhough_savepng(fch, "fo.bmp");
  return 0;
}
